package org.jeecg.modules.demo.weixin.meituan.util;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.modules.demo.weixin.dto.YxMeituanExamineDto;
import org.jeecg.modules.demo.weixin.entity.YxMeituanVerfication;
import org.jeecg.modules.demo.weixin.vo.MeiTuanVo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MeiTuanUtil {

    /**
     * 获取团购信息接口
     */
    @SneakyThrows
    public static JSONObject getGroupBuyingInfo(String shopId, String session) {

        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", "32f155c4849f5fb3");
        requestParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", session);
        requestParam.put("open_shop_uuid", shopId);
        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", SignUtil.signTopRequest(requestParam, AppConstants.APP_SECRET, AppConstants.SIGN_METHOD_MD5));

        //Map转url字符串
        String s = RequestUtil.mapToGetParam(requestParam);
        //发起get请求
        CloseableHttpClient httpClients = HttpClients.createDefault();
        HttpGet get = new HttpGet(AppConstants.getGroupUrl + s);
        CloseableHttpResponse responses = null;
        responses = httpClients.execute(get);
        String contents = EntityUtils.toString(responses.getEntity());
        return JSONObject.parseObject(contents);
    }

    /**
     * 获取商家授权的session接口
     */
    @SneakyThrows
    public static JSONObject getSession(String authCode, String appKey, String appSecret) {
        //接口地址
        String httpUrl = "https://openapi.dianping.com/router/oauth/token?";

        //构造请求参数
        String contents = "";
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", appKey);
        requestParam.put("app_secret", appSecret);
        requestParam.put("auth_code", authCode);
        requestParam.put("grant_type", "authorization_code");
        requestParam.put("redirect_url", "http://192.168.1.56:7010/weixin/meituan/meituan/getSession");//前端组件获取code时使用了回调地址这里也必须写 须一致

        //map转url参数串
        String url = RequestUtil.mapToGetParam(requestParam);

        //发送请求并接受返回数据
        CloseableHttpClient httpClients = HttpClients.createDefault();
        HttpPost post = new HttpPost(httpUrl + url);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        CloseableHttpResponse responses = null;
        responses = httpClients.execute(post);
        contents = EntityUtils.toString(responses.getEntity());
        return JSONObject.parseObject(contents);
    }

    /**
     * 获取店铺id接口
     *
     * @return
     */
    @SneakyThrows
    public static JSONObject getShopId(String session, String bid) {

        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", AppConstants.appKey);
        requestParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", session);
        requestParam.put("bid", bid);
        //验证签名，详情见签名生成说明文档
        requestParam.put("sign", SignUtil.signTopRequest(requestParam, AppConstants.APP_SECRET, AppConstants.SIGN_METHOD_MD5));

        String url = RequestUtil.mapToGetParam(requestParam);
        //发起get请求
        CloseableHttpClient httpClients = HttpClients.createDefault();
        HttpGet get = new HttpGet(AppConstants.getShopUrl + url);
        CloseableHttpResponse responses = null;
        responses = httpClients.execute(get);
        String contents = EntityUtils.toString(responses.getEntity());
        return JSONObject.parseObject(contents);
    }

    /**
     * 校验接口
     * @param session
     * @param qrCode
     * @param openShopUuid
     * @return
     */
    @SneakyThrows
    public static YxMeituanExamineDto examine(String session, String openShopUuid,String qrCode) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", AppConstants.appKey);
        requestParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", session);
        requestParam.put("qr_code", qrCode);
        requestParam.put("open_shop_uuid", openShopUuid);
        //验证签名
        requestParam.put("sign", SignUtil.signTopRequest(requestParam, AppConstants.APP_SECRET, AppConstants.SIGN_METHOD_MD5));

        //将Map数据转为url字符串
        String s = RequestUtil.mapToGetParam(requestParam);
        //发起post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(AppConstants.examineUrl + s);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;UTF-8");
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        String contents = EntityUtils.toString(response.getEntity());
        JSONObject resultBody = JSONObject.parseObject(contents);
        if (!resultBody.get("code").equals(200)) {
            return null;
        }
        YxMeituanExamineDto yxMeituanExamine = JSON.parseObject(resultBody.getJSONArray("data").getJSONObject(0).toString(), YxMeituanExamineDto.class);
        return yxMeituanExamine;
    }

    /**
     *美团核销
     * @param session
     * @param shopid
     * @param receiptCode
     * @return
     */
    @SneakyThrows
    public static YxMeituanVerfication consume(String session,String shopid,String receiptCode) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", AppConstants.appKey);
        requestParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", session);
        requestParam.put("open_shop_uuid",shopid);
        requestParam.put("receipt_code",receiptCode);
        requestParam.put("requestid", RandomUtil.randomString(10));//随机生成10位数字 用于作 请求id
        requestParam.put("count", "1");
        requestParam.put("app_shop_account", "123456");
        requestParam.put("app_shop_accountname", "test123");
        //验证签名
        requestParam.put("sign", SignUtil.signTopRequest(requestParam, AppConstants.APP_SECRET, AppConstants.SIGN_METHOD_MD5));

        //将Map数据转为url字符串
        String s = RequestUtil.mapToGetParam(requestParam);
        //发起post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(AppConstants.consumeUrl + s);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;UTF-8");
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        String contents = EntityUtils.toString(response.getEntity());
        JSONObject resultBody = JSONObject.parseObject(contents);
        if (!resultBody.get("code").equals(200)) {
            return null;
        }
        YxMeituanVerfication meituanVerfication = JSON.parseObject(resultBody.getJSONArray("data").getJSONObject(0).toString(), YxMeituanVerfication.class);
        JSONArray namePhone = resultBody.getJSONArray("data").getJSONObject(0).getJSONArray("payment_detail");
        List<MeiTuanVo> meiTuanVoList = namePhone.stream().map(item -> JSON.parseObject(((JSONObject) item).toString(), MeiTuanVo.class)).collect(Collectors.toList());
        meiTuanVoList.forEach(meiTuanVo -> {
            if (meiTuanVo.getAmountType()==10){
                meituanVerfication.setAmount(meiTuanVo.getAmount()) ;
            }
        });
        return meituanVerfication;
    }

    @SneakyThrows
    public static Object chexiao(String session,String shopid,String receiptCode,String dealId) {
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("app_key", AppConstants.appKey);
        requestParam.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        requestParam.put("format", "json");
        requestParam.put("v", "1");
        requestParam.put("sign_method", "MD5");
        requestParam.put("session", session);
        requestParam.put("open_shop_uuid",shopid);
        requestParam.put("app_deal_id",dealId);
        requestParam.put("receipt_code",receiptCode);
        requestParam.put("requestid", RandomUtil.randomString(10));//随机生成10位数字 用于作 请求id
        requestParam.put("app_shop_account", "123456");
        requestParam.put("app_shop_accountname", "test123");
        //验证签名
        requestParam.put("sign", SignUtil.signTopRequest(requestParam, AppConstants.APP_SECRET, AppConstants.SIGN_METHOD_MD5));

        //将Map数据转为url字符串
        String s = RequestUtil.mapToGetParam(requestParam);
        //发起post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(AppConstants.chexiaoUrl + s);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;UTF-8");
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        String contents = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(contents);
        if (!jsonObject.get("code").equals(200)) {
            return null;
        }
        return jsonObject;
    }


}
